import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { View, Button, Text, Image } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { debounce } from '@/utils/helper';
import NavBar from '@/components/NavBar';
import rightImg from '@/images/common/rightBlack.svg';
import shopBtnImg from '@/orderSubPack/images/confirmOrder/shopBtn.png';
import goodsImg from '@/orderSubPack/images/confirmOrder/goods.png';
import { sourceUrl } from '@/config';
import failImg from '@/images/common/fail.png';
import pTuancanbiaoqian from '@/images/common/tuancanbiaoqian.png';
import pBqTuancan from '@/images/common/bqTuancan.png';
import CouponSelect from '@/orderSubPack/couponSelect/index';
import PointSelect from '@/components/PointSelect/index';
import { getUsableSelectedCouponList, getOrderCouponPayload } from '@/dataTransfer/coupon.js';
import { getOrderPointPayload } from '@/dataTransfer/point.js';
import { AtSwitch } from 'taro-ui';
import classNames from 'classnames';
import locationImg from '@/orderSubPack/images/confirmOrder/location.png';
import zebraLineImg from '@/orderSubPack/images/confirmOrder/zebra-line.png';

import './index.scss';

// 团餐 team
// 点餐配送 delivery
// 到店自取 toShop
const OrderType = {
  team: '团餐',
  delivery: '点餐配送',
  toShop: '到店自取',
};

const Address = ({ addressStr, contactName, mobile }) => {
  if (contactName) {
    return (
      <View
        className="address"
        onClick={() => {
          Taro.navigateTo({ url: '/orderSubPack/takeOutAddress/index' });
        }}
      >
        <Image src={locationImg} className="location-img" />
        <View className="address-inner">
          <View className="user-info clean-white">
            <Text className="name">{contactName}</Text>
            <Text className="mobile">{mobile}</Text>
          </View>
          <View className="detail clean-white">
            <Text className="text">{addressStr}</Text>
          </View>
        </View>
        <Image src={rightImg} className="right-img" />
      </View>
    );
  }

  return (
    <View
      className="noaddress"
      onClick={() => {
        Taro.navigateTo({ url: '/giftCardSubPack/address/index' });
      }}
    >
      <Image src={locationImg} className="location-img" />
      <View className="needAdd">添加新地址</View>
      <Image src={rightImg} className="rightImg" />
    </View>
  );
};

const ShopsDetail = ({ shopData = {} }) => {
  const { orgName, productCarConfirmInfoList = [], favouredType } = shopData;
  return (
    <View className="order-goods clean-white">
      <View className="shop-info">
        <Image src={shopBtnImg} className="shop-img" />
        <Text className="name">{orgName}</Text>
        {favouredType === '1' ? <Image src={pTuancanbiaoqian} className="tc-icon"></Image> : null}
      </View>
      <View className="goods-list">
        {productCarConfirmInfoList.map((product) => {
          const {
            productReleaseName,
            productVariantReleaseId,
            options = '',
            num,
            price,
            imageUrl,
          } = product;
          const specOptions = JSON.parse(options);
          const specStr = Object.values(specOptions).join(' ') || '';
          return (
            <View key={productVariantReleaseId} className="goods-info">
              <View className="imgArea">
                <Image
                  src={
                    imageUrl
                      ? imageUrl.indexOf('http') === 0
                        ? imageUrl
                        : sourceUrl + imageUrl
                      : goodsImg
                  }
                  className="goods-img"
                />
                {product.favouredType == 1 && <Image className="bqImg" src={pBqTuancan} />}
              </View>
              <View className="goods-desc">
                <Text className="name omit">{productReleaseName}</Text>
                <Text className="desc omit">{specStr}</Text>
                <View className="price">
                  <Text className="unit">¥</Text>
                  <Text className="value">{price}</Text>
                </View>
              </View>
              <View className="count clean-white">
                <Text className="text">x</Text>
                <Text className="text">{num}</Text>
              </View>
            </View>
          );
        })}
      </View>
    </View>
  );
};

const OrderSummary = ({
  isExistsGiftCard,
  giftCardSelected,
  expressFee,
  giftCardPrice,
  submitTotalPrice,
  isUsePoint,
  toggleUsePoints,
  isTeam,
  handleOpenCouponOpen,
  usableCouponList,
  disabledCouponList,
  discountAmount,
  packFee = 0,
  handlePointOpen,
  point,
  totalPrice,
}) => {
  return (
    <View className="order-summary">
      <View className="inner">
        <View className="row">
          <Text className="left">商品金额：</Text>
          <View className="right">
            <Text className="unit">¥</Text>
            <Text className="price">{parseFloat(totalPrice).toFixed(2)}</Text>
          </View>
        </View>
        <View className="pack row">
          <View className="left">打包费：</View>
          <View className="right">
            <Text className="unit">¥</Text>
            <Text className="price">{parseFloat(packFee).toFixed(2)}</Text>
          </View>
        </View>
        <View className="express row">
          <View className="left">配送费：</View>
          <View className="right">
            <Text className="unit">¥</Text>
            <Text className="price">{parseFloat(expressFee).toFixed(2)}</Text>
          </View>
        </View>
        {isTeam ? (
          <View className="full-discount row">
            <View className="left">满减优惠：</View>
            <View className="right">未满足使用条件</View>
          </View>
        ) : null}
        <View className="coupon row">
          <View className="left">优惠券：</View>
          <View className="right" onClick={handleOpenCouponOpen}>
            {usableCouponList?.length > 0 ? (
              <>
                <Text className="unit">¥ {parseFloat(discountAmount).toFixed(2)}</Text>
                <Image src={rightImg} className="right-img" />
              </>
            ) : disabledCouponList?.length > 0 ? (
              <Text className="">未满足使用条件</Text>
            ) : (
              <Text className="">无优惠券可用</Text>
            )}
          </View>
        </View>

        <View className="points row">
          <View className="left">积分：</View>
          <View className="right">
            {point && point.maxUsablePoint ? (
              <>
                <View className="text" onClick={handlePointOpen}>
                  可用{point.maxUsablePoint}积分抵用{point.maxPrice}元
                </View>

                <Image src={rightImg} className="point-right-image" />

                <AtSwitch
                  className={classNames('custom-switch', {
                    'switch-h5': process.env.TARO_ENV === 'h5',
                  })}
                  checked={isUsePoint}
                  onChange={toggleUsePoints}
                  border={false}
                />
              </>
            ) : (
              <View className="text no-margin">
                {point?.exceptionCode === '210' ? '今日使用已达上限' : ''}
                {point?.exceptionCode === '211' ? '本订单不支持' : ''}
                {point?.exceptionCode === '212'
                  ? `共${point?.sumPoint}积分，满${point.offsetPointMin}可用`
                  : ''}
                {point?.exceptionCode === undefined ? '暂无可用' : ''}
              </View>
            )}
          </View>
        </View>

        <View className="gift-card row">
          <View className="left">礼品卡：</View>

          <View
            className="right"
            onClick={() =>
              Taro.navigateTo({
                url: '/giftCardSubPack/giftCardSelect/index',
              })
            }
          >
            {giftCardSelected.length > 0 && (
              <Text className="unit active">- ¥ {parseFloat(giftCardPrice).toFixed(2)}</Text>
            )}
            {giftCardSelected.length === 0 && isExistsGiftCard && (
              <>
                <Text className="unit active">有可用卡</Text>
                <Image src={rightImg} className="right-img" />
              </>
            )}
            {giftCardSelected.length === 0 && !isExistsGiftCard && (
              <Text className="unit">无可用卡</Text>
            )}
          </View>
        </View>
      </View>
      <View className="summary">
        <View className="prefix">实付金额：</View>
        <View className="right">
          <Text className="unit">¥</Text>
          <Text className="price">{parseFloat(submitTotalPrice).toFixed(2)}</Text>
        </View>
      </View>
    </View>
  );
};

const ConfirmOrder = ({
  loading,
  dispatch,
  cartShopSelected,
  defaultAddress,
  teamDefaultAddress,
  giftCardSelected,
  eInvoiceSelected,

  usableCouponList,
  disabledCouponList,

  discountAmount,
  point,
}) => {
  const isLoading = [
    loading.effects['order/getOrderConfirmInfo'],
    loading.effects['giftCard/allAddressesModel'],
    loading.effects['otherApi/getTeamAllAddress'],
    loading.effects['giftCard/getOrderCouponList'],
    loading.effects['order/getOrderPoint'],
    loading.effects['order/createTakeawayOrder'],
  ].some((v) => v === true);
  isLoading ? Taro.showLoading({ title: '加载中' }) : Taro.hideLoading();

  const [timeRange, setTimeRange] = useState('');
  const handleDeliveryTimeChange = (t) => {
    setTimeRange(t);
  };

  const [isUsePoint, setIsUsePoint] = useState(false);
  const toggleUsePoints = () => {
    setIsUsePoint(!isUsePoint);
  };

  const [orderDetail, setOrderDetail] = useState({}); // 订单参数详情

  const productCarRequest = cartShopSelected.map((v) => ({ productCarId: v })); // 购物车数据

  const {
    productCarConfirmOrgResponsesList = [],
    expressFee = 0,
    totalPrice = 0,
    packFee = 0,
    favouredId,
  } = orderDetail;
  const orgId = productCarConfirmOrgResponsesList?.[0]?.orgId;

  // ========== 价格计算 =============
  // 总价
  let totalCent = totalPrice * 100 + expressFee * 100 + packFee * 100;

  // 优惠券折扣
  const couponCent = (discountAmount ?? 0) * 100;

  // 积分折扣
  const pointCent = ((isUsePoint && point?.maxPrice) ?? 0) * 100;

  // 礼品卡全部
  const giftCardFullCent = giftCardSelected.reduce((pre, cur) => cur.balance * 100 + pre, 0);

  // 其它折扣使用之后
  let tempCent = totalCent - couponCent - pointCent;
  tempCent = tempCent < 0 ? 0 : tempCent;

  // 礼品卡最大优惠
  const giftCardCent = tempCent < giftCardFullCent ? tempCent : giftCardFullCent;

  const giftCardPrice = giftCardCent / 100;

  // 最终价格
  const submitTotalPrice = (tempCent - giftCardCent) / 100;

  const centMap = { totalCent, couponCent, pointCent, giftCardCent };

  // 订单详情获取后, 获取优惠券价格
  useEffect(() => {
    if (!Object.keys(orderDetail).length) {
      return;
    }

    dispatch({
      type: 'giftCard/getOrderCouponList',
      payload: getOrderCouponPayload(orderDetail),
    });
  }, [orderDetail]);

  // 优惠券获取后, 获取积分 抵扣
  useEffect(() => {
    if (!orderDetail || !Object.keys(orderDetail).length) {
      return;
    }

    if (!usableCouponList) {
      return;
    }

    dispatch({
      type: 'order/getOrderPoint',
      payload: getOrderPointPayload(orderDetail, centMap),
    });
  }, [usableCouponList]);

  // ========== 价格计算结束 =============

  const [isExistsGiftCard, setIsExistsGiftCard] = useState(false);
  // 获取是否存在礼品卡
  useEffect(() => {
    dispatch({
      type: 'fineCard/fineCardGetCardList',
      payload: {
        status: 1,
      },
    }).then((res) => {
      const arr = res.filter((v) => Object.keys(v).length > 0);

      setIsExistsGiftCard(!!arr.length);
    });
  }, []);

  // 获取订单确认详细信息
  useEffect(() => {
    dispatch({
      type: 'order/getOrderConfirmInfo',
      payload: { idList: cartShopSelected },
    })
      .then((res) => {
        setOrderDetail(res);
      })
      .catch(() => {
        Taro.showToast({
          mask: true,
          title: '订单失效',
          image: failImg,
          duration: 2000,
        });
        setTimeout(() => {
          Taro.redirectTo({ url: '/pages/mainPages/cartSin/index' });
        }, 2000);
      });
  }, []);

  const [orderType, setOrderType] = useState('');

  useEffect(() => {
    // 订单数据获取, 判断订单类型
    if (!Object.keys(orderDetail).length) {
      return;
    }
    const isTeam = orderDetail.productCarConfirmOrgResponsesList?.some(({ favouredType }) => {
      return favouredType === '1';
    });
    setOrderType(isTeam ? OrderType.team : OrderType.delivery);
  }, [orderDetail]);

  // 优惠券选择界面
  const [couponSelectIsOpened, setCouponSelectIsOpen] = useState(false);

  // 积分选择界面
  const [pointSelectIsOpened, setPointSelectIsOpen] = useState(false);

  // 有积分的情况下默认关闭选择积分
  useEffect(() => {
    setIsUsePoint(!point?.maxUsablePoint);
  }, [point]);

  // 退出时清空
  useEffect(() => {
    return () => {
      // 优惠券清空
      dispatch({ type: 'giftCard/resetOrderCouponList' });

      // 积分清空
      dispatch({ type: 'order/resetOrderPoint' });

      // 团餐地址清空
      dispatch({ type: 'otherApi/resetTeamAddress' });

      // 非团餐地址清空
      dispatch({
        type: 'productCar/setDefaultAddress',
        payload: {},
      });
    };
  }, []);

  const isTeam = orderType === OrderType.team;

  let addressInfo;
  if (isTeam) {
    if (teamDefaultAddress) {
      addressInfo = teamDefaultAddress;
    }
  } else {
    if (defaultAddress) {
      addressInfo = defaultAddress;
    }
  }

  // 默认地址
  const {
    address,
    houseNumber,
    contactName,
    mobile,
    merchantName,
    addressStr = `${address ?? ''}${houseNumber ?? ''}`,
    latitude,
    longitude,
  } = addressInfo ?? {};

  const personalAddressMobile = defaultAddress?.mobile;
  useEffect(() => {
    // 初始化个人地址
    if (!personalAddressMobile) {
      dispatch({ type: 'giftCard/allAddressesModel' });
    }
  }, [personalAddressMobile]);

  const teamAddressMobile = teamDefaultAddress?.mobile;
  useEffect(() => {
    if (orderType !== OrderType.team) {
      return;
    }

    // 初始化团餐地址
    if (!teamAddressMobile) {
      if (!orgId) {
        return;
      }

      dispatch({ type: 'otherApi/getTeamAllAddress', payload: { orgId } });
    }
  }, [teamAddressMobile, orderType, productCarConfirmOrgResponsesList, orgId]);

  const handleSave = debounce(() => {
    if (!contactName) {
      return Taro.showToast({
        mask: true,
        title: isTeam ? '您暂无可用团餐配送地址' : '请先选择收货地址',
        icon: 'none',
      });
    }

    if (isTeam && !timeRange) {
      return Taro.showToast({
        mask: true,
        title: '请先选择配送时间段',
        icon: 'none',
      });
    }

    const { selectedCouponList } = getUsableSelectedCouponList(usableCouponList);

    let data = {
      addressRequest: {
        ...addressInfo,
        address: addressStr,
        // TODO: 替换写死内容
        city: '苏州',
        cityCode: '0512',
        country: '',
        mobile,
        name: contactName,
        phone: '',
        postcode: '',
        province: '',
        deliveryTime: { startTime: timeRange },
        latitude,
        longitude,
      },
      userSource: 'wechat',
      currency: '4217',
      titleId: eInvoiceSelected.id || '',
      totalPrice: submitTotalPrice,
      giftCardIdList: giftCardSelected?.map((v) => v.id),
      // 备注
      tastePreferenceRequest: {},

      couponList: selectedCouponList?.map((item) => {
        return {
          orgId,
          ...item,
        };
      }),
      pointsList:
        isUsePoint && point?.maxPrice
          ? [
              {
                orgId,
                discountAmount: point.maxPrice,
                usePoints: point.maxUsablePoint,
              },
            ]
          : [],
    };

    data = { ...data, productCarRequest };

    dispatch({
      type: 'order/createTakeawayOrder',
      payload: data,
    }).then(async (e) => {
      // 清除礼品卡选择
      await dispatch({ type: 'productCar/setGiftCardSelect', payload: [] });
      await dispatch({ type: 'productCar/getCartList' });
      Taro.redirectTo({ url: '/orderSubPack/checkstand/affirm/index' });
    });
  }, 2000);

  return (
    <>
      <NavBar title="确认订单" />

      <View className="takeoutConfirmOrder">
        <Address
          {...{
            orgId,
            favouredId,
            isTeam,
            orderType,
            setOrderType,
            addressStr,
            contactName,
            mobile,
            merchantName,
            timeRange,
            dispatch,
            handleDeliveryTimeChange,
          }}
        ></Address>

        <Image src={zebraLineImg} className="zebra-line" />

        <View className="shop-list">
          {productCarConfirmOrgResponsesList.map((shopData) => (
            <ShopsDetail key={shopData.orgId} shopData={shopData} />
          ))}
        </View>

        <View className="order-card order-summary-card">
          <OrderSummary
            {...{
              isExistsGiftCard,
              giftCardSelected,
              totalPrice,
              expressFee,
              giftCardPrice,
              submitTotalPrice,
              isUsePoint: isUsePoint,
              toggleUsePoints,
              isTeam,
              usableCouponList,
              disabledCouponList,
              discountAmount,
              point,
              handlePointOpen: () => {
                setPointSelectIsOpen(true);
              },
              handleOpenCouponOpen: () => {
                setCouponSelectIsOpen(true);
              },
            }}
          ></OrderSummary>
        </View>

        <View className="bottom-card">
          <View className="btn-bottom">
            <Button className="btn" onClick={handleSave}>
              确认支付
            </Button>
          </View>
        </View>
      </View>

      <CouponSelect
        usableCouponList={usableCouponList}
        disabledCouponList={disabledCouponList}
        isOpened={couponSelectIsOpened}
        handleClose={(data) => {
          setCouponSelectIsOpen(false);

          if (data) {
            dispatch({
              type: 'giftCard/setOrderCouponList',
              payload: {
                disabledCouponList: disabledCouponList,
                usableCouponList: data,
              },
            });
          }
        }}
        dispatch={dispatch}
      ></CouponSelect>

      <PointSelect
        point={point}
        isOpened={pointSelectIsOpened}
        handleClose={() => {
          setPointSelectIsOpen(false);
        }}
      ></PointSelect>
    </>
  );
};

export default connect(({ productCar, loading, otherApi, takeOut, giftCard, order }) => ({
  loading,
  cartSelected: productCar.cartSelected,
  cartShopSelected: takeOut.takeOutCartShop,
  defaultAddress: productCar.defaultAddress,
  giftCardSelected: productCar.giftCardSelected,
  eInvoiceSelected: productCar.eInvoiceSelected,

  teamDefaultAddress: otherApi.teamDefaultAddress,
  usableCouponList: giftCard.usableCouponList,
  disabledCouponList: giftCard.disabledCouponList,
  selectedCouponList: giftCard.selectedCouponList,
  discountAmount: giftCard.discountAmount,

  point: order.point,
}))(ConfirmOrder);
